package com.browsesoft.resource;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;

import com.browsesoft.EntityManager;
import com.browsesoft.ExtendElement;
import com.browsesoft.RightTypeManager;
import com.browsesoft.htmlcomponent.HTMLBasicComponent;
import com.browsesoft.htmlcomponent.HTMLBasicModel;
import com.browsesoft.user.User;

/**
 * <p>
 * Title:
 * </p>
 * <p>
 * Description:
 * </p>
 * <p>
 * Copyright: Copyright (c) 2004
 * </p>
 * <p>
 * Company:
 * </p>
 * 
 * @author not attributable
 * @version 1.0
 */
public class LicenseFormModel implements HTMLBasicModel {
	Resource resource;

	Resource byResource;

	Collection rightTypes = new HashSet();

	HTMLBasicComponent com;

	String action;

	LinkedList changed = new LinkedList();

	User user;

	public LicenseFormModel() {
	}

	/**
	 * 初始化
	 * 
	 * @param request
	 * @throws Exception
	 */
	public void init(HttpServletRequest request) throws Exception {
		user = (User) request.getSession().getAttribute("loginUser");
		String resourceId = request.getParameter("resourceid");
		String byResourceId = request.getParameter("point");
		resource = (Resource) EntityManager.getInstance().getObject(resourceId);
		byResource = (Resource) EntityManager.getInstance().getObject(
				byResourceId);
		if (byResource != null) {
			this.rightTypes = this.getRightTypeByRes();
		}
	}

	/**
	 * 服务
	 * 
	 * @param request
	 * @param response
	 * @throws Exception
	 */
	public void service(HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		action = request.getParameter("action");
		String inherit = request.getParameter("isinherit");
		String inherit2 = request.getParameter("isinherit2");
		if (inherit != null && inherit2 != null) {
			setDefaultValue(this.getElement("isinherit"), inherit);
			setDefaultValue(this.getElement("isinherit2"), inherit2);
		}
		if (action != null && !action.equals("")) {
			if (action.equals("isinherit2true")) {
				this.rightTypes = getAllRightTypeByRes();
			} else if (action.equals("isinherit2false")) {
				this.rightTypes = getRightTypeByRes();
				this.changed.clear();
			} else if (action.equals("confirm")) {
				String resourceResult = request
						.getParameter("resourceselected");
				String byResourceResult = request
						.getParameter("byresourceselected");
				String isinherit = request.getParameter("isinherit");
				String isinherit2 = request.getParameter("isinherit2");
				this.addRight(resourceResult, byResourceResult, isinherit,
						isinherit2);
				this.com.getPage().close();
			}
		}
	}

	private void addRight(String resourceResult, String byResourceResult,
			String isinherit, String isinherit2) throws Exception {
		LicensePolicyEntity lp = new LicensePolicyEntity();
		lp.setTableName("t_licensepolicy");
		lp.setEntityType("licensepolicy");
		lp.getAttributes().put("tablename", "t_licensepolicy");
		lp.getAttributes().put("entitytype", "licensepolicy");
		lp.getAttributes().put("parentid", this.resource.getID());
		lp.getAttributes().put("resourceid", this.resource.getID());
		lp.setResource(resource);
		lp.getAttributes().put("byresourceid", this.byResource.getID());
		lp.setByResource(byResource);
		lp.getAttributes().put("isinherit", isinherit);
		lp.getAttributes().put("byisinherit", isinherit2);
		lp.getAttributes().put("resourceresult", resourceResult);
		lp.getAttributes().put("byresourceresult", byResourceResult);
		String rights = getRightTypes(changed);
		lp.getAttributes().put("righttype", rights);
		lp.getAttributes().put(
				"licensepolicy",
				getRemark(resourceResult, byResourceResult, isinherit,
						isinherit2, rights));
		lp.insert();
	}

	private String getRemark(String resourceResult, String byResourceResult,
			String isinherit, String isinherit2, String rights) {
		String discription = "";
		// 是否是英文显示
		if (isEnShow()) {
			discription = getEnDiscription(resourceResult, byResourceResult,
					isinherit, isinherit2, rights);
		} else {
			discription = getChDiscription(resourceResult, byResourceResult,
					isinherit, isinherit2, rights);
		}

		return discription;
	}
	
	private String getEnDiscription(String resourceResult,
			String byResourceResult, String isinherit, String isinherit2,
			String rights)
	{
		String result = " Authorize";
		String name = (String) this.resource.getAttributes().get("name");
		result += " " + name + " ";
		if (isinherit.equals("yes")) {
			result += " and its sub-modules ";
			if (resourceResult != null && !resourceResult.equals("")) {
				result += " except of ";
				String[] ids = resourceResult.split(",");
				for (int i = 0; i < ids.length; i++) {
					Resource r = (Resource) EntityManager.getInstance()
							.getObject(ids[i]);
					name = (String) r.getAttributes().get("name");
					if (i < ids.length - 1) {
						result += name + ",";
					} else {
						result += name + " ";
					}
				}
			}
		}
		result += " with competences as follows ";
		name = (String) this.byResource.getAttributes().get("name");
		result += " " + name + " ";
		if (isinherit2.equals("yes")) {
			result += " and its sub-modules ";
			if (byResourceResult != null && !byResourceResult.equals("")) {
				result += " except the competences of ";
				String[] ids = byResourceResult.split(",");
				for (int i = 0; i < ids.length; i++) {
					Resource r = (Resource) EntityManager.getInstance()
							.getObject(ids[i]);
					name = (String) r.getAttributes().get("name");
					if (i < ids.length - 1) {
						result += name + ",";
					} else {
						result += name + " ";
					}
				}
			}
		}
		return result;
	}

	private String getChDiscription(String resourceResult,
			String byResourceResult, String isinherit, String isinherit2,
			String rights) {
		String result = " 给";
		String name = (String) this.resource.getAttributes().get("name");
		result += " " + name + " ";
		if (isinherit.equals("是")) {
			result += " 及其所有子 ";
			if (resourceResult != null && !resourceResult.equals("")) {
				result += " 不包括 ";
				String[] ids = resourceResult.split(",");
				for (int i = 0; i < ids.length; i++) {
					Resource r = (Resource) EntityManager.getInstance()
							.getObject(ids[i]);
					name = (String) r.getAttributes().get("name");
					if (i < ids.length - 1) {
						result += name + ",";
					} else {
						result += name + " ";
					}
				}
			}
		}
		result += " 授予 ";
		name = (String) this.byResource.getAttributes().get("name");
		result += " " + name + " ";
		if (isinherit2.equals("是")) {
			result += " 及其所有子 ";
			if (byResourceResult != null && !byResourceResult.equals("")) {
				result += " 不包括 ";
				String[] ids = byResourceResult.split(",");
				for (int i = 0; i < ids.length; i++) {
					Resource r = (Resource) EntityManager.getInstance()
							.getObject(ids[i]);
					name = (String) r.getAttributes().get("name");
					if (i < ids.length - 1) {
						result += name + ",";
					} else {
						result += name + " ";
					}
				}
			}
		}
		result += "的 " + rights + " 权限";
		return result;
	}

	private boolean isEnShow() {
		if (this.com.getElement().hasAttribute("en")) {
			return true;
		}
		return false;
	}

	private Collection getAllRightTypeByRes() {
		Collection result = new HashSet();
		result.addAll(this.getRightTypeByRes());
		Collection children = byResource.getAllChildrens();
		Iterator iter = children.iterator();
		Collection temp = new LinkedList();
		while (iter.hasNext()) {
			Resource item = (Resource) iter.next();
			String type = item.getType();
			if (!temp.contains(type)) {
				temp.add(type);
				LinkedList ls = RightTypeManager.getRightType(item.getType());
				if (ls != null && ls.size() > 0) {
					result.addAll(ls);
				}
			}
		}
		return result;
	}

	private Collection getRightTypeByRes() {
		Collection nodeLists = new HashSet();
		// 判断这个节点所对于的资源是否有多种权限类型
		Collection list = RightTypeManager.getRightType(this.byResource
				.getType());
		if (list != null && list.size() > 0) {
			nodeLists.addAll(list);
			return nodeLists;
		}
		// 返回权限节点链表
		return nodeLists;
	}

	public void setComponent(HTMLBasicComponent component) {
		com = component;
	}

	public void updatePageElement(HTMLBasicComponent c) throws Exception {
		if (action != null && !action.equals("")) {
			// 资源不及联
			if (action.equals("isinheritfalse")) {
				this.clearSelected("resourceselected");
				this.getElement("filtrate").setAttribute("style",
						"display:none");
				this.getElement("cancelfiltrate").setAttribute("style",
						"display:none");
			} // 资源及联
			else if (action.equals("isinherittrue")) {
				this.getElement("filtrate").removeAttribute("style");
				this.getElement("cancelfiltrate").setAttribute("style",
						"display:none");
			} // style不及联
			else if (action.equals("isinherit2false")) {
				this.clearSelected("byresourceselected");
				this.getElement("filtrate2").setAttribute("style",
						"display:none");
				this.getElement("cancelfiltrate2").setAttribute("style",
						"display:none");
			} // 被资源及联
			else if (action.equals("isinherit2true")) {
				this.getElement("filtrate2").removeAttribute("style");
				this.getElement("cancelfiltrate2").setAttribute("style",
						"display:none");
			} // 过滤
			else if (action.equals("filtrate")) {
				this.getElement("cancelfiltrate").removeAttribute("style");
			} // 取消过滤
			else if (action.equals("cancelfiltrate")) {
				// 清空选项
				clearSelected("resourceselected");
				this.getElement("cancelfiltrate").setAttribute("style",
						"display:none");
			} // 被 过滤
			else if (action.equals("filtrate2")) {
				this.getElement("cancelfiltrate2").removeAttribute("style");
			} // 被 取消过滤
			else if (action.equals("cancelfiltrate2")) {
				// 清空选项
				clearSelected("byresourceselected");
				this.getElement("cancelfiltrate2").setAttribute("style",
						"display:none");
			} else {
				LinkedList ls = ExtendElement.findElements(this.com
						.getElement(), "righttype", "righttype");
				for (int i = 0; i < ls.size(); i++) {
					Element e = (Element) ls.get(i);
					String name = e.getAttribute("name");
					if (action.equals(name + "true")) {
						e.setAttribute("checked", "true");
						this.changed.add(action);
					} else if (action.equals(name + "false")) {
						e.removeAttribute("checked");
						this.changed.remove(name + "true");
					}
				}
				Iterator iter = changed.iterator();
				while (iter.hasNext()) {
					String item = (String) iter.next();
					if (item.endsWith("true")) {
						LinkedList ll = ExtendElement.findElements(this.com
								.getElement(), "name", item.substring(0, item
								.length() - 4));
						if (ll.size() == 1) {
							Element eee = (Element) ll.get(0);
							eee.setAttribute("checked", "true");
						}
					}
				}
			}
		}
	}

	// 清空选项
	public void clearSelected(String name) {
		this.getElement(name).setAttribute("value", "");
	}

	public Collection getRights() {
		return this.rightTypes;
	}

	private Element getElement(String value) {
		Element element = com.getElement();
		return (Element) ExtendElement.findElements(element, "name", value)
				.get(0);
	}

	/**
	 * 如果是被选中的，设置selected选项
	 */
	public void setDefaultValue(Element dealElement, String value)
			throws Exception {
		NodeList nodelist = dealElement.getChildNodes();
		for (int i = 0; i < nodelist.getLength(); i++) {
			// 是OPTION元素
			if (nodelist.item(i).getNodeType() == Node.ELEMENT_NODE) {
				Element element = (Element) nodelist.item(i);
				Text text = (Text) ExtendElement.findElementContext(element)
						.get(0);
				String context = (String) text.getData();
				if (context.equals(value)) {
					element.setAttribute("selected", "selected");
				} else {
					element.removeAttribute("selected");
				}
			}
		}
	}

	public void setRightElement(Element node, String rightType, Document doc) {
		ExtendElement
				.replaceElementContext(node, doc.createTextNode(rightType));
		Element e = (Element) ExtendElement.findElements(node, "righttype",
				"righttype").get(0);
		e.setAttribute("name", rightType);
	}

	private String getRightTypes(LinkedList changed) {
		String result = "";
		Iterator iter = changed.iterator();
		while (iter.hasNext()) {
			String item = (String) iter.next();
			item = item.substring(0, item.length() - 4);
			result += item + ",";
		}
		if (result.endsWith(",")) {
			result = result.substring(0, result.length() - 1);
		}
		return result;
	}
}